/*
 * 文 件 名:  XmlHelper.java
 * 版    权:  深圳埃思欧纳信息咨询有限公司版权所有. YYYY-YYYY,  All rights reserved
 * 描    述:  <描述>
 * 修 改 人:  honny.huang
 * 修改时间:  2011-9-13
 * 跟踪单号:  <跟踪单号>
 * 修改单号:  <修改单号>
 * 修改内容:  <修改内容>
 */
package com.dom4j;

import java.io.File;  
import java.io.FileInputStream;  
import java.io.FileNotFoundException;  
import java.io.FileOutputStream;  
import java.io.IOException;  
import java.io.InputStream;  
import java.lang.reflect.Field;  
import java.text.SimpleDateFormat;  
import java.util.Date;  
import java.util.HashMap;  
import java.util.Iterator;  
import java.util.List;  
import java.util.Map;  
import java.util.Set;  
import org.apache.log4j.Logger;  
import org.dom4j.Document;  
import org.dom4j.DocumentException;  
import org.dom4j.Element;  
import org.dom4j.XPath;  
import org.dom4j.io.SAXReader;  
import org.dom4j.io.XMLWriter;  

/**
 * xml处理类
 * 
 * @author  honny.huang
 * @version  [版本号, 2011-9-13]
 * @see  [相关类/方法]
 * @since  [产品/模块版本]
 */
public class XmlHelper {  
    private String filename;  
    private Document document;  
    static Logger logger=Logger.getLogger(XmlHelper.class);  
    /** 
     * 路径的包含的xml文件只需要有根节点就可，否则不是合法的xml文件无法解析 
     * */  
    public XmlHelper(String filename){  
        this.filename=filename;  
        SAXReader reader = new SAXReader();  
        File file = new File(filename);  
        InputStream is=null;  
        try {  
            is = new FileInputStream(file);  
            this.document=reader.read(is);  
        } catch (FileNotFoundException e) {  
            logger.info("未找到"+filename+"这个文件");  
        } catch (DocumentException e) {  
            logger.error(e);  
        }  
    }  
    /** 
     * 清除原来根节点中的内容,如果保存之前不清楚的话，是在文档后追加，而不是重新写入 
     */  
    public void clear(){  
        document.getRootElement().clearContent();  
    }  
    /** 
     * 保存xml到指定路径 
     * */  
    public void save(String filename) throws IOException{  
        //此处最好不要用FileWriter,会出现中文乱码  
        XMLWriter out = new XMLWriter(new FileOutputStream(this.filename));  
        out.write(document);  
        out.flush();  
        out.close();  
    }  
    public XPath getXPath(Element element, String nsUrl, String nsName, String selectUrl){  
        Map nsMap = new HashMap();  
        nsMap.put(nsName, nsUrl);  
        XPath xPath = element.createXPath(selectUrl);  
        xPath.setNamespaceURIs(nsMap);  
        return xPath;  
  }  
    public void save() throws IOException{  
      save(this.filename);  
    }  
    /** 
     * 将指定对象转成xml表达的字符串 
     * */  
    public String format(Object object){  
        Element element=document.getRootElement();  
        try{  
            if(  
                    object instanceof Integer||  
                    object instanceof Double||  
                    object instanceof String||  
                    object instanceof Character||  
                    object instanceof Byte||  
                    object instanceof Long||  
                    object instanceof Float||  
                    object instanceof Short  
                ){  
                    throw new IllegalArgumentException();  
                }else if(object instanceof List<?>){  
                    insertList(element, (List<?>)object);  
                }else if(object instanceof Map<?, ?>){  
                    insertMap(element, (Map<?,?>)object);  
                }else if(object instanceof Set<?>){  
                    insertSet(element, (Set<?>)object);  
                }else if(object instanceof Object[]){  
                    insertArray(element, (Object[])object);  
                }else {  
                    insertObject(element,object);  
                }  
        }catch(IllegalAccessException e1){  
            e1.printStackTrace();  
        }catch(IllegalArgumentException e2){  
            e2.printStackTrace();  
        }  
        return document.asXML();  
    }  
    public static Element insertObject(Element element,Object object) throws IllegalArgumentException, IllegalAccessException{  
        if(object!=null){  
            Class<?> clazz=object.getClass();  
            //类节点的名字  
            String classEName=toLowerHead(clazz.getSimpleName());  
            Field[] fields=clazz.getDeclaredFields();  
            Element classElement=element.addElement(classEName);  
            for(Field field:fields){  
                String name=field.getName();  
                field.setAccessible(true);  
                Object fieldObj=field.get(object);  
                if(fieldObj==null){  
                    classElement.addAttribute(name, "");  
                }else if(  
                    fieldObj instanceof Integer||  
                    fieldObj instanceof Double||  
                    fieldObj instanceof String||  
                    fieldObj instanceof Character||  
                    fieldObj instanceof Byte||  
                    fieldObj instanceof Long||  
                    fieldObj instanceof Float||  
                    fieldObj instanceof Short  
                ){  
                    String value=field.get(object).toString();  
                    classElement.addAttribute(name, value);  
                }else if(fieldObj instanceof Date){  
                    Date date=(Date)fieldObj;  
                    SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
                    String value=format.format(date);  
                    classElement.addAttribute(name, value);  
                }else{  
                    Element child=classElement.addElement(name);  
                    if(fieldObj instanceof List<?>){  
                        insertList(child, (List<?>)fieldObj);  
                    }else if(fieldObj instanceof Map<?, ?>){  
                        insertMap(child, (Map<?,?>)fieldObj);  
                    }else if(fieldObj instanceof Set<?>){  
                        insertSet(child, (Set<?>)fieldObj);  
                    }else if(fieldObj instanceof Object[]){  
                        insertArray(child, (Object[])fieldObj);  
                    }else {  
                        insertObject(child,fieldObj);  
                    }  
                }  
            }  
        }  
        return element;  
    }  
    public static Element insertList(Element element,List<?> list) throws IllegalArgumentException, IllegalAccessException {  
        for(Object object:list){  
            insertObject(element, object);  
        }  
        return element;  
    }  
    public static Element insertMap(Element element,Map<?, ?> map) throws IllegalArgumentException, IllegalAccessException{  
        Iterator<?> iterator=map.values().iterator();  
        while(iterator.hasNext()){  
            Object object=iterator.next();  
            insertObject(element, object);  
        }  
        return element;  
    }  
    public static Element insertSet(Element element,Set<?> set) throws IllegalArgumentException, IllegalAccessException{  
        Iterator<?> iterator=set.iterator();  
        while(iterator.hasNext()){  
            Object object=iterator.next();  
            insertObject(element, object);  
        }  
        return element;  
    }  
    public static Element insertArray(Element element,Object[] array) throws IllegalArgumentException, IllegalAccessException {  
        for(Object obj:array){  
            insertObject(element, obj);  
        }  
        return element;  
    }  
    public static String toLowerHead(String simpleName){  
        String begin=simpleName.substring(0,1).toLowerCase();  
        String other=simpleName.substring(1,simpleName.length());  
        return begin+other;  
    }  
}  